package nccloud.arap.bill.basdisc.action;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import nc.vo.arap.bastradisc.AggBasDiscVO;
import nc.vo.arap.bastradisc.BasDiscBVO;
import nc.vo.arap.bastradisc.BasDiscVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nccloud.arap.bill.basdisc.bill.util.CommonUtil;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.ui.pattern.billcard.BillCardOperator;

public class AutoDataBasDiscAction implements ICommonAction {

	@Override
	public Object doAction(IRequest paramIRequest) {
		
		BillCardOperator billCardOperator = new BillCardOperator();
	      // 1、获取AGGVO （request转换主子VO）
		AggBasDiscVO oldbillvo = billCardOperator.toBill(paramIRequest);
		
		BasDiscVO oldheadvo = oldbillvo.getParentVO();
	
		String pk_org =  oldheadvo.getPk_org();
		String cperiod =  oldheadvo.getCperiod();
		String transtype =  oldheadvo.getTranstype();
		
		if(StringUtils.isEmpty(pk_org)) {
			ExceptionUtils.wrapBusinessException("组织不能为空");
		}
		
		if(StringUtils.isEmpty(cperiod)) {
			ExceptionUtils.wrapBusinessException("应收月份不能为空");
		}
		
		if(StringUtils.isEmpty(transtype)) {
			ExceptionUtils.wrapBusinessException("交易类型不能为空");
		}
		
		AggBasDiscVO newbillvo = null;
		try {
			newbillvo = CommonUtil.getFinancingcostMaintainService().queryMonthBefore(pk_org, transtype,cperiod);
		} catch (BusinessException | ParseException e) {
			e.printStackTrace();
		}
		
		if(newbillvo!=null) {

			List<BasDiscBVO> allBodyList = new ArrayList<BasDiscBVO>();
			
			BasDiscBVO[] oldbodyVOs = oldbillvo.getBodyVOs();
			
			for(BasDiscBVO bodyVO : oldbodyVOs) {
				if(StringUtils.isNotEmpty(bodyVO.getPrimaryKey())) {
					bodyVO.setStatus(VOStatus.DELETED);
					allBodyList.add(bodyVO);
				}
			}
			
			BasDiscBVO[] newbodyVOs = newbillvo.getBodyVOs();
			
			for(BasDiscBVO bodyVO : newbodyVOs) {
				bodyVO.setPk_basdisc(null);
				bodyVO.setPk_basdisc_b(null);
				bodyVO.setStatus(VOStatus.NEW);
				allBodyList.add(bodyVO);
			}
			
			BasDiscBVO[] allBody = new BasDiscBVO[allBodyList.size()];
			allBodyList.toArray(allBody);
			
			oldbillvo.setChildrenVO(allBody);
			
			Object billcard = billCardOperator.toCard(oldbillvo);
			
			return billcard;
		}else {
			ExceptionUtils.wrapBusinessException("无法获取到上一个应收月份数据");
		}
		
		return null;
	}

}
